package com.jq.util;

import com.jq.conf.Connection;
import com.jq.conf.CollectionsListWrapper;
import org.apache.commons.io.FileUtils;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * 软件配置
 */
public class ConfUtil {

    static File file;

    static {
        String userDir = System.getProperties().getProperty("user.home");
        file = new File(userDir + "/" + ".easyZK/conf.xml");
        try {
            FileUtils.forceMkdirParent(file);
            file.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void save(String name, String url) {
        try {
            JAXBContext context = JAXBContext
                    .newInstance(CollectionsListWrapper.class);
            Marshaller m = context.createMarshaller();
            m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
            CollectionsListWrapper wrapper = new CollectionsListWrapper();
            //加载之前保存的数据
            List<Connection> list = load();
            list.add(new Connection(name, url));
            wrapper.setConnections(list);

            m.marshal(wrapper, file);

        } catch (Exception e) { // catches ANY exception
            e.printStackTrace();
        }
    }

    public static void overwrite(List<Connection> list) {
        try {
            JAXBContext context = JAXBContext
                    .newInstance(CollectionsListWrapper.class);
            Marshaller m = context.createMarshaller();
            m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
            CollectionsListWrapper wrapper = new CollectionsListWrapper();
            wrapper.setConnections(list);

            m.marshal(wrapper, file);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void defeteFile() {
        try {
            file.delete();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static List<Connection> load() {
        List<Connection> connections = new ArrayList<>();
        try {
            JAXBContext context = JAXBContext.newInstance(CollectionsListWrapper.class);
            Unmarshaller um = context.createUnmarshaller();
            // Reading XML from the file and unmarshalling.
            CollectionsListWrapper wrapper = (CollectionsListWrapper) um.unmarshal(file);
            connections = wrapper.getConnections();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return connections;
    }

    public static void main(String[] args) throws IOException {
//        load(new File("d:/a.xml"));
//        save();
        String userDir = System.getProperties().getProperty("user.home");
        System.out.println(userDir);
//        FileUtils.forceMkdir(new File(userDir+"/"+".zkui"));
    }
}
